﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Krile.Common;

namespace Twinkle.URLShortener.Services
{
    public class TinyURL : URLShortenerBase
    {
        const string ServiceURL = "http://tinyurl.com";
        const string APIURL = "http://tinyurl.com/api-create.php?url=";

        public override bool IsCompressed(string url)
        {
            return url.StartsWith(ServiceURL);
        }

        public override bool TryCompress(string url, out string compressed)
        {
            if (url.StartsWith(ServiceURL))
            {
                //already compressed
                compressed = url;
                return true;
            }
            compressed = null;
            if (String.IsNullOrEmpty(url))
                return false;
            var escaped = Uri.EscapeDataString(url);
            var nc = new NetConnect();
            try
            {
                var ret = nc.WebConnectDownloadString(new Uri(APIURL + escaped), "GET", null);
                if (ret.Succeeded && !String.IsNullOrEmpty(ret.Data))
                {
                    compressed = ret.Data;
                    if (compressed == "Error")
                        return false;
                    else
                        return true;
                }
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public override bool TryDecompress(string url, out string decompressed)
        {
            decompressed = null;
            return false;
        }
    }
}
